﻿using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

//访问接口为： page?d=081205

public partial class ADPVCount : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string date = Request.QueryString["d"];

        //处理错误日期
        if (string.IsNullOrEmpty(date) || date.Length != 6)
        {
            //Response.Write("请正确输入日期");
            Response.End();
        }
        
        //处理文件名
        string path = @"D:\wwwroot\W3SVC1\ex" + date + ".log";
        string line;
        string[] cols;
        int uri;
        int status;
        int siteid;
        const int MAX_SITE = 1000;
        int[] list = new int[MAX_SITE * 2];

        //转换日期
        date = "20" + date.Substring(0, 2) + "-" + date.Substring(2, 2) + "-" + date.Substring(4, 2);
        if (date == DateTime.Now.ToShortDateString())
        {
            Response.Write("不能统计今日日志");
            Response.End();
        }
        Response.Write(DateTime.Now.ToLocalTime() + "<br>");

        
        //访问代码为200，号码为/00/数字/格式
        if (File.Exists(path))
        {

            StreamReader sr = new StreamReader(path);
            uri = -1;
            status = -1;

            //文件处理开始
            while (sr.Peek() >= 0)
            {
                line = sr.ReadLine();
                if (line.StartsWith("#Fields: "))
                {
                    cols = line.Split(" ".ToCharArray());
                    uri = GetIndex(cols, "cs-uri-stem");
                    status = GetIndex(cols, "sc-status");
                }
                else if (uri < 0 || status < 0 || line.StartsWith("#") || line.Length == 0)
                {
                    //排除错误行
                    continue;
                }
                else
                {
                    cols = line.Split(" ".ToCharArray());
                    if (cols.Length < uri + 1 || cols.Length < status + 1)
                    {
                        continue;
                    }
                    if (cols[status] == "200" && cols[uri].Length > 10)
                    {
                        //最关键的业务逻辑，即什么是社区？
                        if (Regex.IsMatch(cols[uri], "^/[/0-9]{9}/"))
                        {
                            siteid = int.Parse(cols[uri].Substring(1, 9).Replace("/", ""));
                            UpdatePV(list, siteid);
                        }
                    }
                        //排除首页
                    else if (cols[uri].ToLower() == "/index.asp")
                    {
                        UpdatePV(list, 30);
                    }
                }
            }
            sr.Close();
            //一定要记住，关掉文件句柄


                SqlConnection conn = new SqlConnection();
                    conn.ConnectionString = ConfigurationManager.ConnectionStrings["GoWLLConnectionString"].ConnectionString;
            
            
            conn.Open();
                SqlTransaction tran = conn.BeginTransaction();
                SqlCommand cmd = new SqlCommand();
            
            cmd.Connection = conn;
            cmd.Transaction = tran;
            
                cmd.CommandText = "delete from [GowllPV] where [date]='" + date + "'";
                cmd.ExecuteNonQuery();

            //给每个社区插入现行值
            for (int i = 0; i < list.Length; i += 2)
            {
                if (list[i] == 0)
                {
                    break;
                }
                else
                {
                    cmd.CommandText = "insert into [GowllPV]([date],[CommunityID],[PV])values('"
                        + date + "'," + list[i] + "," + (list[i + 1] * 100) + ")";
                        //*100表示放大100倍
                    cmd.ExecuteNonQuery();
                    //Response.Write(cmd.CommandText+"<br>\n");
                }
            }
            tran.Commit();
            cmd.Dispose();
            tran.Dispose();
            conn.Close();
            conn.Dispose();
        }
        Response.Write(DateTime.Now.ToLocalTime());
    }
    
    //获取列的列号
    int GetIndex(string[] cols, string name)
    {
        for (int i = 1; i < cols.Length; i++)
        {
            if (cols[i] == name) return i - 1;
        }
        return -1;
    }

    //属于站点PV的累加器
    void UpdatePV(int[] list, int siteid)
    {
        for (int i = 0; i < list.Length; i += 2)
        {
            if (list[i] == 0)
            {
                list[i] = siteid;
                list[i + 1] = 1;
                break;
            }
            else if (list[i] == siteid)
            {
                list[i + 1]++;
                break;
            }
        }
    }
    //函数结束
}
